package com.sphd.education.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.sphd.education.EducationApplication;
import com.sphd.education.R;
import com.sphd.education.base.BaseActivity;
import com.sphd.education.info.ClassifyTwo;
import com.sphd.education.info.MyInfo;
import com.sphd.education.modle.EducationUrl;
import com.sphd.education.view.tagview.TagCloudView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/*
我的资料设置
*
* */
public class MySelfActivity extends BaseActivity {

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.my_image)
    ImageView myImage;
    @Bind(R.id.my_userid)
    TextView myUserid;
    @Bind(R.id.my_nickname)
    TextView myNickname;
    @Bind(R.id.my_sex)
    TextView mySex;
    @Bind(R.id.my_age)
    TextView myAge;
    @Bind(R.id.my_birthday)
    TextView myBirthday;
    @Bind(R.id.my_userphone)
    TextView myUserphone;
    @Bind(R.id.my_signing)
    TextView mySigning;
    @Bind(R.id.interest_lesson_tag_cloud_view)
    TagCloudView interestLessonTagCloudView;
    @Bind(R.id.myself_linear)
    LinearLayout myselfLinear;
    private MyInfo myInfo;
    Intent intent;
    private List<String> interestList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_self);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        initView();

    }

    @Override
    public void initView() {
        toolbar.setTitle("个人资料");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        interestList = new ArrayList<String>();
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();//这是自带的箭头的返回的监听
            }
        });
        intent = new Intent();
        findViewById();
    }

    @Override
    public void findViewById() {
        myInfo = DataSupport.findLast(MyInfo.class);
        ImageLoader.getInstance().displayImage(EducationUrl.HttpTitle + myInfo.getUserimgurl(),
                myImage, EducationUrl.setImg(R.mipmap.touxiangweishangchuan));
        myUserid.setText(myInfo.getUserid() + "");
        myNickname.setText(myInfo.getName());
        mySex.setText(myInfo.getGender());
        if (TextUtils.isEmpty(myInfo.getBirthday())){
            myBirthday.setText(myInfo.getBirthday());
        }else {
            Date dbDate = null;
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                dbDate = (Date) dateFormat.parse(myInfo.getBirthday());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String strDate=dateFormat.format(dbDate);
            myBirthday.setText(strDate);
            try {
                if (getAge(dbDate)<=0){
                    myAge.setText("出生日期选择错误，请重试。");
                }else {
                    myAge.setText(getAge(dbDate)+"岁");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        myUserphone.setText(myInfo.getUsername());
        mySigning.setText(myInfo.getDescription());
        if (myInfo.getLikes().trim().length() > 0) {
            String[] strlikes = myInfo.getLikes().split(",");
            if (strlikes.length > 0) {
                String lesson = "\t";
                for (int i = 0; i < strlikes.length; i++) {
                    interestList.add(DataSupport.where("classifytwo_id = ?", Integer.valueOf(strlikes[i].trim()) + "").
                            find(ClassifyTwo.class).get(0)
                            .getClassify());
                }
                interestLessonTagCloudView.setTags(interestList);
            }
        }
    }

    @Override
    public void myNet() {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_myself, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.menu_finish_btn) {
            intent.setClass(this, FinishMySelfActivity.class);
            intent.putExtra("myInfo", myInfo);
            startActivityForResult(intent, 1);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == 1) {
                StringRequest stringRequest = new StringRequest(Request.Method.POST, EducationUrl.HttpTitle + EducationUrl.MyInfoMessage
                        , new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(response);
                            if (jsonObject.has("avatar")) {
                                myInfo.setUserimgurl(jsonObject.getString("avatar"));
                            }
                            if (jsonObject.has("birthday")) {
                                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                Date dbDate = (Date) dateFormat.parse(jsonObject.getString("birthday").trim());
                                String strDate = dateFormat.format(dbDate);
                                Log.e("dbDate", strDate);
                                myInfo.setBirthday(strDate);
                            }
                            if (jsonObject.has("description")) {
                                myInfo.setDescription(jsonObject.getString("description"));
                            }
                            if (jsonObject.has("gender")) {
                                myInfo.setGender(jsonObject.getString("gender"));
                            }
                            if (jsonObject.has("id")) {
                                myInfo.setUserid(jsonObject.getInt("id"));
                            }
                            if (jsonObject.has("likes")) {
                                myInfo.setLikes(jsonObject.getString("likes"));
                            }
                            if (jsonObject.has("mobile")) {
                                myInfo.setUsername(jsonObject.getString("mobile"));
                            }
                            if (jsonObject.has("realName")) {
                                myInfo.setName(jsonObject.getString("realName"));
                            }
                            myInfo.save();
                            interestList.clear();
                            findViewById();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> map = new HashMap<>();
                        map.put("mobile", myInfo.getUsername());
                        return map;
                    }
                };
                EducationApplication.getRequestQueue().add(stringRequest);
            }
        }
    }
    public static int getAge(Date birthDay) throws Exception {
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth;
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                //monthNow==monthBirth
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                } else {
                    //do nothing
                }
            } else {
                //monthNow>monthBirth
                age--;
            }
        } else {
            //monthNow<monthBirth
            //donothing
        }

        return age;
    }
}
